package com.fancy.mobileschool.ui;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.fancy.mobileschool.R;
import com.fancy.mobileschool.ui.adapt.StringAdapter;
import com.fancy.mobileschool.util.Spider;

import java.util.ArrayList;
import java.util.List;



public class NewsListActivity extends Activity {

    private List<String> urls;
    private List<String> titles;
    private Context context;
    private StringAdapter stringAdapter=null;
    private ListView listView;




    private SwipeRefreshLayout swipeRefreshLayout;
    int i=15;//max count of News list


    Handler handler=new Handler()
    {
        public void handleMessage(android.os.Message msg) {
          if(msg.what==1)
          {
              stringAdapter=new StringAdapter(titles,context);
              listView.setAdapter(stringAdapter);
              stringAdapter.notifyDataSetChanged();
              swipeRefreshLayout.setRefreshing(false);

          }
        };
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.newslist);
        context=NewsListActivity.this;
        listView= (ListView) findViewById(R.id.newlist_lv);

        swipeRefreshLayout= (SwipeRefreshLayout) findViewById(R.id.newlist_srl);


        titles=new ArrayList<String>();
        urls=new ArrayList<String>();

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent=new Intent(NewsListActivity.this,HduNewsPageActivity.class);
                intent.putExtra("url",urls.get(i));
                startActivity(intent);
            }
        });

        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                swipeRefreshLayout.setRefreshing(true);
                titles.clear();
                urls.clear();
                new gettitlesThread().start();
            }
        });

        swipeRefreshLayout.setRefreshing(true);
        new gettitlesThread().start();


    }


    class gettitlesThread extends Thread {
        @Override
        public void run() {
            //


            titles= Spider.getTitles(i);
            urls=Spider.getUrls(i);
            handler.sendEmptyMessage(1);
        }
    }



}
